package com.edu.study.base.rest;

import com.edu.base.ums.member.domain.ClsMember;
import com.edu.base.ums.member.service.IClsMemberService;
import com.edu.study.base.StuQuestionPaper.domain.StuQuestionPaper;
import com.edu.study.base.StuQuestionPaper.service.IStuQuestionPaperService;
import com.edu.study.base.StuTestScoreLevel.service.IStuTestScoreLevelService;
import com.edu.study.base.stuQuestionCatalog.domain.StuQuestionCatalog;
import com.edu.study.base.stuQuestionCatalog.service.IStuQuestionCatalogService;
import com.edu.study.base.stuQuestionLibrary.domain.StuQuestionLibraryRy;
import com.edu.study.base.stuQuestionLibrary.service.IStuQuestionLibraryRyService;
import com.edu.study.base.stuQuestionOption.service.IStuQuestionOptionService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Api(tags = "3、能力测试相关接口")
@RestController
@RequestMapping("/api/questionPaper/")
public class AppQuestionPaperController extends BaseController {

    @Autowired
    private IStuQuestionPaperService questionPaperService;

    @Autowired
    private IStuQuestionCatalogService questionCatalogService;

    @Autowired
    private IStuQuestionLibraryRyService questionLibraryRyService;
    @Autowired
    private IClsMemberService clsMemberService;

    @Autowired
    private IStuQuestionOptionService questionOptionService;

    @Autowired
    private IStuTestScoreLevelService stuTestScoreLevelService;
    @Autowired
    private RedisCache redisCache;

    @ApiOperation(value = "查询所有题卷目录")
    @GetMapping("/getQuestionPaperList")
    public AjaxResult getQuestionPaper() {
        StuQuestionPaper questionPaper = new StuQuestionPaper();
        List<StuQuestionPaper> stuQuestionPapers = questionPaperService.selectStuQuestionPaperList(questionPaper);
        return AjaxResult.success(stuQuestionPapers);
    }


    @ApiOperation(value = "根据题卷id获取能力测试题")
    @GetMapping("/getQuestionPaperById")
    @ApiImplicitParam(name = "id", value = "题卷id", required = true, dataType = "Long")
    public AjaxResult getQuestionPaperById(Long id) {

        StuQuestionCatalog rootcatalog = null;//顶级目录
//        rootcatalog = redisCache.getCacheObject("question_catalog_" + id);
//        if(rootcatalog!=null){
//            return AjaxResult.success(rootcatalog);
//        }
        StuQuestionPaper questionPaper = questionPaperService.selectStuQuestionPaperById(id);
        if (questionPaper != null) {
            rootcatalog = new StuQuestionCatalog();
            Long catalogId = questionPaper.getCatalogId();//题卷目录id
            rootcatalog.setId(catalogId);
            rootcatalog.setName(questionPaper.getName());
            //查询题卷目录
            StuQuestionCatalog questionCatalog = new StuQuestionCatalog();
            List<StuQuestionCatalog> all = questionCatalogService.selectQuestionCatalogList(questionCatalog);
            builderCatalog(rootcatalog, all);
            //redisCache.setCacheObject("question_catalog_" + id,rootcatalog);
            return AjaxResult.success(rootcatalog);
        } else {
            return AjaxResult.success("无此题卷");
        }


    }

    //递归构建目录层级级目录下的试题
    public void builderCatalog(StuQuestionCatalog qc, List<StuQuestionCatalog> all) {
        List<StuQuestionCatalog> childrenCatalogList = all.stream().filter(a -> a.getParentId().equals(qc.getId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(childrenCatalogList)) {
            qc.setChildren(childrenCatalogList);
            for (StuQuestionCatalog catalog : childrenCatalogList) {
                catalog = builderQuestionCatalog(catalog);
                builderCatalog(catalog, all);
            }
        } else {
            if (StringUtils.isNotEmpty(qc.getQuestionTypeId() + "")) {
                StuQuestionLibraryRy stuQuestionLibraryRy = new StuQuestionLibraryRy();
                stuQuestionLibraryRy.setQuestionTypeId(qc.getQuestionTypeId());
                stuQuestionLibraryRy.setQuestionCatalogId(qc.getId());
                List<StuQuestionLibraryRy> libraryList = questionLibraryRyService.getQuestionLibraryListByQuestionPaperId(stuQuestionLibraryRy);//题卷下所有的题
                qc.setLibraryRyList(libraryList);
//                    for(StuQuestionLibraryRy questionLibrary : libraryList){
//                        StuQuestionOption questionOption = new StuQuestionOption();
//                        questionOption.setQuestionLibraryId(questionLibrary.getId());
//                        List<StuQuestionOption> optionList = questionOptionService.selectStuQuestionOptionList(questionOption);
//                        questionLibrary.setOptionList(optionList);
//                    }
            }
        }

    }

    private StuQuestionCatalog builderQuestionCatalog(StuQuestionCatalog qc){
        StuQuestionLibraryRy stuQuestionLibraryRy = new StuQuestionLibraryRy();
        stuQuestionLibraryRy.setQuestionCatalogId(qc.getId());
        List<StuQuestionLibraryRy> libraryList = questionLibraryRyService.getQuestionLibraryListByQuestionPaperId(stuQuestionLibraryRy);//题卷下所有的题
        if(!CollectionUtils.isEmpty(libraryList)){
            StuQuestionLibraryRy questionLibrary = libraryList.get(0);
            qc.setQuestionAudioUrl(questionLibrary.getQuestionAudioUrl());
            qc.setQuestionRemark(questionLibrary.getQuestionRemark());
            qc.setQuestionWord(questionLibrary.getQuestionWord());
        }
        return qc;
    }


    @ApiOperation(value = "根据能力测试的得分获取解锁阶梯等级和用户等级")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true),
            @ApiImplicitParam(name = "score", value = "能力测试得分", required = true)
    })

    @GetMapping("/getLevelByScore")
    public AjaxResult getLevelByScore(String memberId, Double score) {
        ClsMember clsMember = clsMemberService.selectClsMemberById(memberId);
        if (clsMember == null) {
            return AjaxResult.error("无此会员用户");
        }
        AjaxResult ajaxResult = AjaxResult.success();
        int level = stuTestScoreLevelService.getLevelByScore(score);//阶梯等级
        int userLevel = 0; //用户等级
        if (level <= 20 && score > 0) {
            userLevel = 1;//初级
        } else if (level > 20 && level <= 40) {
            userLevel = 2;//中级
        } else if (level > 40 && level <= 60) {
            userLevel = 3;//高级
        } else if (level > 60 && level <= 80) {
            userLevel = 4;//超越级
        } else if (level > 80 && level <= 100) {
            userLevel = 5;//精通级
        }

        //默认能力测试次数是2 每测试一次减一，直到为0
        if (clsMember.getTestTimes() > 0 && clsMember.getTestTimes() <= 2) {
            clsMember.setTestTimes(clsMember.getTestTimes() - 1);
        }
        clsMember.setHighLevel(Long.valueOf(level));
        clsMember.setScore(BigDecimal.valueOf(score));
        clsMemberService.updateClsMember(clsMember);
        ajaxResult.put("unlockLevel", level);
        ajaxResult.put("userLevel", userLevel);
        ajaxResult.put("TestTimes", clsMember.getTestTimes());
        return ajaxResult;
    }


    /**
     * 随机获得一套能力练习
     *
     * @return
     */
    @ApiIgnore
    @ApiOperation("随机获得一套能力测试题")
    @GetMapping("/getAblityTestQuestionPaper")
    public AjaxResult getAblityTestQuestionPaper(@RequestParam("name") String name) {
        StuQuestionCatalog catalog = questionCatalogService.selectTreeDataByName(name);
        if (catalog == null)
            return AjaxResult.error("题库目录配置错误或者无此配置");
        //查询所有的能力测试题，随机选择一套
        StuQuestionPaper paper = new StuQuestionPaper();
        paper.setCatalogId(catalog.getId());
        paper.setEnabled(true);
        List<StuQuestionPaper> paperList = questionPaperService.selectStuQuestionPaperList(paper);
        if (paperList != null && paperList.size() > 0) {
            int size = paperList.size();
            Random random = new Random();
            StuQuestionPaper stuQuestionPaper = paperList.get(random.nextInt(size));
            if (stuQuestionPaper != null) {
                //查询当前题卷模板
//                StuQuestionCatalog catalog = questionCatalogService.selectTreeDataById(stuQuestionPaper.getCatalogId());
                StuQuestionLibraryRy stuQuestionLibraryRy = new StuQuestionLibraryRy();
                stuQuestionLibraryRy.setQuestionPaperId(stuQuestionPaper.getId());
                List<StuQuestionLibraryRy> libraryList = questionLibraryRyService.getQuestionLibraryListByQuestionPaperId(stuQuestionLibraryRy);//题卷下所有的题
                //遍历题卷模板，将对应的题放到对映的目录下
                if (catalog != null) {
                    setChildrenLibrary(catalog, libraryList);
                    stuQuestionPaper.setCatalog(catalog);
                    return AjaxResult.success(stuQuestionPaper);
                }
            }
        }
        return AjaxResult.error();
    }


    //将对应的题放入到对应的目录中
    private void setChildrenLibrary(StuQuestionCatalog child, List<StuQuestionLibraryRy> libraryList) {
        if (child.getQuestionTypeId() != null && child.getQuestionTypeId() > 0) {
            List<StuQuestionLibraryRy> list = libraryList.stream().filter(e -> {
                return e.getQuestionTypeId().longValue() == child.getQuestionTypeId().longValue();
            }).collect(Collectors.toList());
            child.setLibraryRyList(list);
        } else {
            List<StuQuestionCatalog> children = child.getChildren();
            if (children != null && children.size() > 0) {
                for (StuQuestionCatalog catalog : children) {
                    setChildrenLibrary(catalog, libraryList);
                }
            }
        }
    }


}
